package com.siwei.mes.service.laboratory.factory.concrete.service;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.ConvertUtils;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKzqd;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.concrete.DataConcreteKz;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.ConcreteLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.concrete.ConcreteLaboratoryFactory;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 混凝土抗折强度
 *
 * @Description: 混凝土抗折强度
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/28 22:08
 */
@Service
public class ConcreteKzqdFactory extends LaboratoryAbstractService implements ConcreteLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");
    @Resource
    private ConcreteLaboratoryMapper concreteLaboratoryMapper;
    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CONCRETE_PARAM_KZQD;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail) {
        log.info("开始上传到协会数据库：【混凝土-{}】", testProjectEnum.getName());
        ConcreteKzqd concreteKzqd = objJson.toJavaObject(ConcreteKzqd.class);
        if (concreteKzqd == null) {
            log.info("【混凝土-{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        DataConcreteKz dataConcreteKz = new DataConcreteKz();
        if (StringUtils.isNotBlank(concreteKzqd.getDdsjqd())) {
            dataConcreteKz.setConclusion(concreteKzqd.getDdsjqd() + "%");
        }
        dataConcreteKz.setFullyMeetTheDesignStrength(NullUtils.ifNull(concreteKzqd.getDdsjqd()));
        dataConcreteKz.setEquivalentToTheStandardIntensity(NullUtils.ifNull(concreteKzqd.getZsbzqd()));
        dataConcreteKz.setAverageFlexuralStrength(NullUtils.ifNull(concreteKzqd.getPjz()));
        dataConcreteKz.setXsws(2);

        String ypdj = experiment.getSampleLevel();
        if (StringUtils.isNotBlank(ypdj)) {
            String mesTpzToKz = ConvertUtils.getMesTpzToKzyq(ypdj);
            if (org.apache.commons.lang.StringUtils.isNotBlank(mesTpzToKz)) {
                mesTpzToKz = mesTpzToKz + "MPa";
                dataConcreteKz.setBzz(NullUtils.ifNull(mesTpzToKz));
            }
        }

        for (ConcreteKzqd.KzInfo kz : concreteKzqd.getKz28d()) {
            if ("1".equals(kz.getIndex())) {
                dataConcreteKz.setWidth1(NullUtils.ifNull(kz.getKz()));
                dataConcreteKz.setHigh1(NullUtils.ifNull(kz.getGz()));
                dataConcreteKz.setSupportDistance1(NullUtils.ifNull(kz.getZj()));
                dataConcreteKz.setDetectionOfPre1(NullUtils.ifNull(kz.getYqqk()));
                dataConcreteKz.setDamageToLoad1(NullUtils.ifNull(kz.getPhhz()));
                dataConcreteKz.setFlexuralStrength1(NullUtils.ifNull(kz.getKzqd()));
                dataConcreteKz.setFractureSurfacesPosition1(NullUtils.ifNull(kz.getZt()));
                dataConcreteKz.setAfterDetection1(NullUtils.ifNull(kz.getYhqk()));
            } else if ("2".equals(kz.getIndex())) {
                dataConcreteKz.setWidth2(NullUtils.ifNull(kz.getKz()));
                dataConcreteKz.setHigh2(NullUtils.ifNull(kz.getGz()));
                dataConcreteKz.setSupportDistance2(NullUtils.ifNull(kz.getZj()));
                dataConcreteKz.setDetectionOfPre2(NullUtils.ifNull(kz.getYqqk()));
                dataConcreteKz.setDamageToLoad2(NullUtils.ifNull(kz.getPhhz()));
                dataConcreteKz.setFlexuralStrength2(NullUtils.ifNull(kz.getKzqd()));
                dataConcreteKz.setFractureSurfacesPosition2(NullUtils.ifNull(kz.getZt()));
                dataConcreteKz.setAfterDetection2(NullUtils.ifNull(kz.getYhqk()));
            } else if ("3".equals(kz.getIndex())) {
                dataConcreteKz.setWidth3(NullUtils.ifNull(kz.getKz()));
                dataConcreteKz.setHigh3(NullUtils.ifNull(kz.getGz()));
                dataConcreteKz.setSupportDistance3(NullUtils.ifNull(kz.getZj()));
                dataConcreteKz.setDetectionOfPre3(NullUtils.ifNull(kz.getYqqk()));
                dataConcreteKz.setDamageToLoad3(NullUtils.ifNull(kz.getPhhz()));
                dataConcreteKz.setFlexuralStrength3(NullUtils.ifNull(kz.getKzqd()));
                dataConcreteKz.setFractureSurfacesPosition3(NullUtils.ifNull(kz.getZt()));
                dataConcreteKz.setAfterDetection3(NullUtils.ifNull(kz.getYhqk()));
            }
        }


        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataConcreteKz, "水泥检测室", concreteKzqd.getJcrq(), detail);

        dataConcreteKz.setSampleName("混凝土抗折试件");

        DataConcreteKz data_jgcl_hnt_kzqdBySampleNo = concreteLaboratoryMapper.findDATA_JGCL_HNT_KZQDBySampleNo(sampleNo);

        if (data_jgcl_hnt_kzqdBySampleNo == null) {
            concreteLaboratoryMapper.addDATA_JGCL_HNT_KZQD(dataConcreteKz);
        } else {
            //修改
            concreteLaboratoryMapper.updateDATA_JGCL_HNT_KZQD(dataConcreteKz);
        }

        //项目id 默认为0
        String parameterID = "0";

        String jcrq = concreteKzqd.getJcrq();

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        DataDefaultUc defaultUc = new DataDefaultUc();
        if (StringUtils.isNotBlank(concreteKzqd.getDdsjqd())) {
            defaultUc.setConclusion(concreteKzqd.getDdsjqd() + "%");
            defaultUc.setUcResultValue(concreteKzqd.getDdsjqd() + "%");
        }

        //获取标准值
        for (CheckBatchConfig projectInfo : batchConfigList) {
            if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KZQD.getCode())) {
                defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
            }
        }

        //根据物料信息设置判断配置
        for (TestProjectSpecConfig test : testProjectSpecConfigList) {
            if (TestProjectEnum.CONCRETE_PARAM_KZQD.getCode().equals(test.getTestProjectCode())) {
                if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                    String json = test.getObjJson();
                    super.setUcStandardValue(defaultUc, json, "kzqd");
                }
            }
        }

        //赋值
        super.setDefUc(defaultUc, experiment, "水泥检测室", sampleNo, jcrq, detail);

        defaultUc.setUcParameterID(parameterID);//项目id

        defaultUc.setSampleName("混凝土抗折试件");

        //新增或修改DataDefaultUc
        super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap) {
        log.info("开始下载协会数据到品控：【混凝土-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        ConcreteKzqd concreteKzqd = objJson.toJavaObject(ConcreteKzqd.class);
        if (concreteKzqd == null) {
            log.info("【混凝土-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }

        //根据样品编码查询协会混凝土抗折强度信息
        DataConcreteKz data = concreteLaboratoryMapper.findDATA_JGCL_HNT_KZQDBySampleNo(sampleNo);
        if (data == null) {
            log.info("根据样品编码查询协会混凝土抗折强度信息为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }

        // 试件尺寸是从 Item_Spec 获取的
        String specName = uploadLaboratoryMapper.findItemGradeBySampleID(sampleNo);
        if (StringUtils.isNotBlank(specName)) {
            concreteKzqd.setSjcc(specName.replace("mm", "").replace("×", "*"));
        }

        concreteKzqd.setDdsjqd(NullUtils.ifNull(data.getFullyMeetTheDesignStrength()));
        concreteKzqd.setZsbzqd(NullUtils.ifNull(data.getEquivalentToTheStandardIntensity()));
        concreteKzqd.setPjz(NullUtils.ifNull(data.getAverageFlexuralStrength()));

        if (data.getDetectonDate() != null) {
            Date detectonDate = data.getDetectonDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            concreteKzqd.setJcrq(strDate);
        }

        for (ConcreteKzqd.KzInfo kz : concreteKzqd.getKz28d()) {
            if (kz.getIndex() != null && "1".equals(kz.getIndex())) {
                kz.setKz(NullUtils.ifNull(data.getWidth1(), kz.getKz()));
                kz.setGz(NullUtils.ifNull(data.getWidth1(), kz.getGz()));
                kz.setZj(NullUtils.ifNull(data.getSupportDistance1(), kz.getZj()));
                kz.setYqqk(NullUtils.ifNull(data.getDetectionOfPre1(), kz.getYqqk()));
                kz.setPhhz(NullUtils.ifNull(data.getDamageToLoad1(), kz.getPhhz()));
                kz.setKzqd(NullUtils.ifNull(data.getFlexuralStrength1(), kz.getKzqd()));
                kz.setZt(NullUtils.ifNull(data.getFractureSurfacesPosition1(), kz.getZt()));
                kz.setYhqk(NullUtils.ifNull(data.getAfterDetection2(), kz.getYhqk()));
            } else if (kz.getIndex() != null && "2".equals(kz.getIndex())) {
                kz.setKz(NullUtils.ifNull(data.getWidth2(), kz.getKz()));
                kz.setGz(NullUtils.ifNull(data.getHigh2(), kz.getGz()));
                kz.setZj(NullUtils.ifNull(data.getSupportDistance2(), kz.getZj()));
                kz.setYqqk(NullUtils.ifNull(data.getDetectionOfPre2(), kz.getYqqk()));
                kz.setPhhz(NullUtils.ifNull(data.getDamageToLoad2(), kz.getPhhz()));
                kz.setKzqd(NullUtils.ifNull(data.getFlexuralStrength2(), kz.getKzqd()));
                kz.setZt(NullUtils.ifNull(data.getFractureSurfacesPosition2(), kz.getZt()));
                kz.setYhqk(NullUtils.ifNull(data.getAfterDetection2(), kz.getYhqk()));
            } else if (kz.getIndex() != null && "3".equals(kz.getIndex())) {
                kz.setKz(NullUtils.ifNull(data.getWidth3(), kz.getKz()));
                kz.setGz(NullUtils.ifNull(data.getHigh3(), kz.getGz()));
                kz.setZj(NullUtils.ifNull(data.getSupportDistance3(), kz.getZj()));
                kz.setYqqk(NullUtils.ifNull(data.getDetectionOfPre3(), kz.getYqqk()));
                kz.setPhhz(NullUtils.ifNull(data.getDamageToLoad3(), kz.getPhhz()));
                kz.setKzqd(NullUtils.ifNull(data.getFlexuralStrength3(), kz.getKzqd()));
                kz.setZt(NullUtils.ifNull(data.getFractureSurfacesPosition3(), kz.getZt()));
                kz.setYhqk(NullUtils.ifNull(data.getAfterDetection3(), kz.getYhqk()));
            }
        }

        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(concreteKzqd);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.getEquipment()));
        detail.setTemperature(NullUtils.ifNull(data.getTemperature()));
        detail.setHumidness(NullUtils.ifNull(data.getHumidity()));
        detail.setExperimentGist(NullUtils.ifNull(data.getDetectonRuleCode()));
        detail.setJudgeGist(NullUtils.ifNull(data.getAccessRuleCode()));

        if (parameterMap.containsKey(detail.getTestProjectCode())) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }
        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}

